package com.ecar.api.support.util;

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class WXValidator {

	public static boolean checkSignature(HttpServletRequest request, String token) {
		try {
			String signature = request.getParameter("signature");
			String timestamp = request.getParameter("timestamp");
			String nonce = request.getParameter("nonce");
			return checkSignature(signature, timestamp, nonce, token);
		} catch (Exception e) {
			return false;
		}
	}

	public static boolean checkSignature(String signature, String timestamp, String nonce, String token) {
		String[] checkInfos = new String[] { token, timestamp, nonce };
		Arrays.sort(checkInfos);
		return signature.equals(SHA1(StringUtils.join(checkInfos)));
	}

	public static String SHA1(String inStr) {
		MessageDigest md;
		String outStr = null;
		try {
			md = MessageDigest.getInstance("SHA-1");
			byte[] digest = md.digest(inStr.getBytes());
			outStr = byteToStr(digest);
		} catch (NoSuchAlgorithmException nsae) {
			nsae.printStackTrace();
		}
		return outStr;
	}

	private static String byteToHexStr(byte ib) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		char[] ob = new char[2];
		ob[0] = Digit[(ib >>> 4) & 0X0F];
		ob[1] = Digit[ib & 0X0F];

		return new String(ob);
	}

	private static String byteToStr(byte[] byteArray) {
		String strDigest = "";
		for (byte aByte : byteArray) {
			strDigest += byteToHexStr(aByte);
		}
		return strDigest;
	}
}
